package org.changs.nav.mvp;

import android.app.Activity;
import android.content.Intent;

import org.changs.aplug.ActivityManager;
import org.changs.aplug.base.BaseActivity;
import org.changs.aplug.base.BasePresenter;
import org.changs.aplug.base.BaseView;
import org.changs.nav.delegate.amap.domain.PoiPoint;
import org.changs.nav.delegate.amap.domain.SimpleLocation;
import org.changs.nav.delegate.global.AmapLocationTask;
import org.changs.nav.delegate.global.AmapNavHelper;
import org.changs.nav.ui.nav.MapNavActivity;
import org.changs.s3.common.tools.NavTools;

import javax.inject.Inject;

import aplug.data.db.CollectInfoHelper;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by yincs on 2017/10/20.
 */

public class MainPresenter extends BasePresenter<BaseActivity> {

    private final RouteListPresenter mRouteListPresenter;
    private final AmapNavHelper mAmapNavHelper;
    private final CollectInfoHelper mCollectInfoHelper;
    private final AmapLocationTask mAmapLocationTask;
    private MyView mMyView;

    @Inject
    public MainPresenter(RouteListPresenter routeListPresenter, AmapNavHelper amapNavHelper,
                         CollectInfoHelper collectInfoHelper, AmapLocationTask amapLocationTask) {
        this.mRouteListPresenter = routeListPresenter;
        this.mAmapNavHelper = amapNavHelper;
        this.mCollectInfoHelper = collectInfoHelper;
        mAmapLocationTask = amapLocationTask;
    }

    public void handleIntent(Intent intent) {
        if (intent == null) {
            Activity preActivity = ActivityManager.getInstance().getPreActivity();
            if (preActivity != null) {
                preActivity.startActivity(new Intent(preActivity, preActivity.getClass()));
            }
            return;
        }
        final int type = intent.getIntExtra(NavTools.EXTRA_TYPE, -1);
        if (type == NavTools.TYPE_GO_HOME) {
            mCollectInfoHelper.findOne(CollectInfoHelper.HOME_ID)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(collectInfo -> {
                        if (!collectInfo.isValid()) {
                            if (isAttachView()) getMvpView().onError("请先设置家的地址");
                        } else {
                            routeCalculate(collectInfo.getLat(), collectInfo.getLon(), collectInfo.getName());
                        }
                    });
        } else if (type == NavTools.TYPE_GO_COMPANY) {
            mCollectInfoHelper.findOne(CollectInfoHelper.COMPANY_ID)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(collectInfo -> {
                        if (!collectInfo.isValid()) {
                            if (isAttachView()) getMvpView().onError("请先设置公司的地址");
                        } else {
                            routeCalculate(collectInfo.getLat(), collectInfo.getLon(), collectInfo.getName());
                        }
                    });
        } else {
            final double lat = intent.getDoubleExtra(NavTools.EXTRA_LAT, 0);
            final double lon = intent.getDoubleExtra(NavTools.EXTRA_LNG, 0);
            final String name = intent.getStringExtra(NavTools.EXTRA_NAME);
            routeCalculate(lat, lon, name);
        }
    }

    private void routeCalculate(double lat, double lon, String name) {
        if (lat == 0 || lon == 0) return;
        Runnable calculate = () -> {
            mAmapNavHelper.prepareNav(new PoiPoint(name, "", lat, lon));
            mRouteListPresenter.calculate();
        };

        if (mAmapLocationTask.getLocation() == null) {
            AmapLocationTask.OnLocationListener listener = new AmapLocationTask.OnLocationListener() {
                @Override
                public void onLocationChanged(int code, String msg, SimpleLocation location) {
                    if (mAmapLocationTask.getLocation() != null) {
                        mAmapLocationTask.unregisterListener(this);
                        calculate.run();
                    }
                }
            };
            mAmapLocationTask.registerListener(listener);
            getMvpView().showLoading().setMessage("正在获取您当前的位置")
                    .cancelAction(() -> mAmapLocationTask.unregisterListener(listener));
        } else {
            calculate.run();
        }
    }

    @Override
    public void attachView(BaseActivity iView) {
        super.attachView(iView);
        mMyView = new MyView(iView);

        mRouteListPresenter.attachView(mMyView);
    }

    @Override
    public void detachView() {
        super.detachView();
        mRouteListPresenter.detachView();
    }

    private class MyView extends BaseView implements RouteListContract.V {

        public MyView(BaseActivity host) {
            super(host);
        }

        @Override
        public void showRouteList(int[] ints, int select) {
            mRouteListPresenter.clickStartNav(ints[0]);
        }

        @Override
        public void startNavView() {
            MapNavActivity.start(getContext());
        }
    }
}
